package net.oschina.simpleplus.servreg;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;

public class ZooKeeperServReg{
    private ZooKeeper zooKeeper;

    public void connect(String hosts) throws IOException, InterruptedException{
		connect(hosts, 30);
	}
	
    
	public void connect(String hosts, int sessionTimeout) throws IOException, InterruptedException{
		CountDownLatch countDownLatch = new CountDownLatch(1);
		zooKeeper = new ZooKeeper(hosts, sessionTimeout, event->{
			if (event.getState() == KeeperState.SyncConnected) {
				countDownLatch.countDown();
			}
		});
		countDownLatch.await();
	}
	
	
	public List<String> getChildren(String path) throws KeeperException, InterruptedException{
		return zooKeeper.getChildren(path, false);
	}


	public void create(String path, byte[] data) throws KeeperException, InterruptedException {
		zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
	}
	
	public void close(){
		try {
			zooKeeper.close();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
